package logic

import (
	"context"
	"srv/models/mysqlinit"
	"time"

	"srv/internal/svc"
	"srv/srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdmListHouseLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAdmListHouseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdmListHouseLogic {
	return &AdmListHouseLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AdmListHouseLogic) AdmListHouse(in *srv.AdmListHouseRequest) (*srv.AdmListHouseResponse, error) {
	// todo: add your logic here and delete this line

	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var count int64
	var u []mysqlinit.House
	query := mysqlinit.DB.Debug().Model(&mysqlinit.House{})
	if in.StartPricer > 0 {
		query = query.Where("house_price>=?", in.StartPricer)
	}
	if in.EndPricer > 0 {
		query = query.Where("house_price<=?", in.EndPricer)
	}
	if in.HouseStatus == 0 {
		query.Count(&count).Offset(int(offset)).Limit(int(pageSize)).Find(&u)

	} else {
		query.Count(&count).Offset(int(offset)).Limit(int(pageSize)).Where("House_status = ?", in.HouseStatus).Find(&u)

	}
	var list []*srv.AdmListHouse
	for _, m := range u {
		listHouse := srv.AdmListHouse{
			UserId:      int64(m.UserId),
			City:        m.City,
			Address:     m.Address,
			HouseCode:   m.HouseCode,
			HouseFloor:  m.HouseFloor,
			HouseAcre:   m.HouseAcre,
			HousePrice:  float32(m.HousePrice),
			Describe:    m.Describe,
			CreatedAt:   m.CreatedAt.Format(time.DateTime),
			HouseStatus: int64(m.HouseStatus),
		}
		list = append(list, &listHouse)
	}
	return &srv.AdmListHouseResponse{
		List:  list,
		Count: count,
	}, nil
}
